﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using RestSharp;

namespace QQConnectSdkSample
{
    //http://wiki.connect.qq.com/%E4%BD%BF%E7%94%A8authorization_code%E8%8E%B7%E5%8F%96access_token
    public partial class AuthenticationPage : PhoneApplicationPage
    {
        //private string appId = "204134";
        //private string appkey = "4c46ac3122a0ccb5ebf14b2a77de3516";
        //private string returnUrl = "win8charm.com";

        private string appId = "101184353";
        private string appkey = "4193d99a0a138e603fa79f00610a6a6d";
        private string returnUrl = "http://www.manhuadao.cn";
        private string stateKey = "ComicIsland";

        
        public AuthenticationPage()
        {
            InitializeComponent();

            string requestUrl = string.Format("https://graph.qq.com/oauth2.0/authorize?display=mobile&response_type=code&client_id={0}&client_secret={1}&state={2}&scope=get_user_info,list_album,upload_pic,do_like&redirect_uri={3}",appId,appkey,stateKey, returnUrl );
           
            this.wb.Navigate(new Uri(requestUrl, UriKind.Absolute));
        }

        private void wb_Navigating(object sender, NavigatingEventArgs e)
        {
            Debug.WriteLine(e.Uri.ToString());
            //https://graph.qq.com/oauth2.0/authorize?display=mobile&response_type=code&client_id=204134&client_secret=4c46ac3122a0ccb5ebf14b2a77de3516&state=AAAA&scope=get_user_info,list_album,upload_pic,do_like&redirect_uri=win8charm.com
            //http://xui.ptlogin2.qq.com/cgi-bin/xlogin?appid=716027609&pt_3rd_aid=204134&style=35&s_url=http://connect.qq.com&refer_cgi=authorize&which=&display=mobile&response_type=code&client_id=204134&client_secret=4c46ac3122a0ccb5ebf14b2a77de3516&state=AAAA&scope=get_user_info,list_album,upload_pic,do_like&redirect_uri=win8charm.com
            //http://win8charm.com/?code=962D4E87D2CB287A5BB95CC29688E0A3&state=AAAA
            //http://win8charm.com/process/route/56970085.html
            //http://ww21.win8charm.com/
            //if (e.Uri.ToString().Contains("win8charm.com/?code="))
            if (e.Uri.ToString().Contains("http://www.manhuadao.cn/?code=") && e.Uri.ToString().Contains("state=ComicIsland"))//http://www.manhuadao.cn/?code=076E1C5A114CFF38713A5EEA1BCAEDF2&state=ComicIsland
            {
                this.wb.Visibility = System.Windows.Visibility.Collapsed;
                //获取AccessToken请求的code                
                Dictionary<string, string> keyValues = GetQueryString(e.Uri.Query);
                string searchKey = keyValues["code"];

                int startIndex = e.Uri.Query.IndexOf("code=");
                int endIndex = e.Uri.Query.IndexOf("&", startIndex);
                string code = e.Uri.Query.Substring(startIndex + 5, endIndex - 1 - 5);
                string requestUrlAccessToken = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&code=" + code + "&client_id=204134&client_secret=4c46ac3122a0ccb5ebf14b2a77de3516&redirect_uri=win8charm.com";
                Debug.WriteLine("requestUrlAccessToken:\t", requestUrlAccessToken);
                //this.wb.Navigate(new Uri(requestUrlAccessToken, UriKind.Absolute));

                var client = new RestClient(requestUrlAccessToken);
                var rest = new RestRequest(Method.GET);
                client.ExecuteAsync(rest, (response) =>
                {

                    //access_token=0D4B86A9DE2FECB09CC3CD647F52923D&expires_in=7776000&refresh_token=9EE1DB8BEA8BDE2DEB761715356B9470
                    Debug.WriteLine("accessToken：\t" + response.Content);
                    //获取AccessToken
                    string accessToken = ParseAccessToken(response.Content);
                    //获取OpenId
                    this.GetOpenId(accessToken);
                });
            }
        }

        private void wb_Navigated(object sender, NavigationEventArgs e)
        {

        }

        void GetOpenId(string accessToken)
        {
            string requestUrlOpenId = "https://graph.qq.com/oauth2.0/me?access_token=" + accessToken;
            var client = new RestClient(requestUrlOpenId);
            var rest = new RestRequest(Method.GET);
            client.ExecuteAsync(rest, (response) =>
            {
                Debug.WriteLine("GetOpenId:\t" + response.Content);
                //callback( {"client_id":"204134","openid":"11123A039593134E4CFD4DE719A1A78D"} );
                string openId = ParseOpenId(response.Content);
                this.GetUserInfo("204134", accessToken, openId);
            });
        }

        void GetUserInfo(string clientId,string accessToken,string openId)
        {
            string requestUrlUserInfo = string.Format("https://graph.qq.com/user/get_user_info?access_token={0}&oauth_consumer_key={1}&openid={2}",accessToken,clientId,openId);
            var client = new RestClient(requestUrlUserInfo);
            var rest = new RestRequest(Method.GET);
            client.ExecuteAsync(rest, (response) =>
            {
                Debug.WriteLine("GetUserInfo:\t" + response.Content);
            });
        }

        string ParseOpenId(string callback)
        {
            string key = "\"openid\":\"";
            int startIndex = callback.IndexOf(key);
            int endIndex = callback.IndexOf("\"", startIndex+key.Length);
            string openId = string.Empty;
            openId = callback.Substring(startIndex + key.Length, endIndex - startIndex - key.Length);
            return openId;
        }

        string ParseAccessToken(string accessToken)
        {
            string key = "access_token=";
            int startIndex = accessToken.IndexOf(key);
            int endIndex = accessToken.IndexOf("&", startIndex);
            string code = string.Empty;
            code = accessToken.Substring(startIndex + key.Length, endIndex - key.Length);
            return code;
        }




        public static Dictionary<string, string> GetQueryString(string queryString)
        {
            queryString = queryString.Replace("?", "");
            Dictionary<string, string> result = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(queryString))
            {
                int count = queryString.Length;
                for (int i = 0; i < count; i++)
                {
                    int startIndex = i;
                    int index = -1;
                    while (i < count)
                    {
                        char item = queryString[i];
                        if (item == '=')
                        {
                            if (index < 0)
                            {
                                index = i;
                            }
                        }
                        else if (item == '&')
                        {
                            break;
                        }
                        i++;
                    }
                    string key = null;
                    string value = null;
                    if (index >= 0)
                    {
                        key = queryString.Substring(startIndex, index - startIndex);
                        value = queryString.Substring(index + 1, (i - index) - 1);
                    }
                    else
                    {
                        key = queryString.Substring(startIndex, i - startIndex);
                    }

                    result[key] = value;
                    if ((i == (count - 1)) && (queryString[i] == '&'))
                    {
                        result[key] = string.Empty;
                    }
                }
            }
            return result;
        }

    }
}